<template>
  <div>
    <a-popover
      trigger="click"
      v-model="visible"
      placement="bottomRight"
      :overlayStyle="{ width: '300px' }"
    >
      <template slot="content">
        <!-- <a-spin :spinning="loadding">
        <a-tabs>
          <a-tab-pane v-for="(tab, k) in 10" tab="标题啊啊啊" :key="k"> </a-tab-pane>
        </a-tabs>
        </a-spin>-->
        <div class="msg-title">消息({{ noticeTotal }})</div>
        <div class="title-line"></div>
        <div class="list">
          <div
            class="item"
            v-for="(item, index) in noticeData"
            :key="index"
            @click="toDetails(item)"
          >
            <div class="item-title">
              <div class="title-left">{{ item.titile }}</div>
              <button class="title-right" v-if="isLeader === 1" @click.stop="clickBuy">续费</button>
            </div>
            <div class="item-content">{{ item.msgAbstract }}</div>
            <div class="item-time">
              <div class="time-left">{{ formatTime(item) }}</div>
              <div class="time-right">{{ item.readMsg }}</div>
            </div>
            <div class="item-line"></div>
          </div>
        </div>
        <div class="title-line"></div>
        <div class="bottom">
          <button class="bottom-more" @click="moreNotice">更多</button>
          <button class="bottom-clear" @click="clearNotice">清空消息</button>
        </div>
      </template>
      <span @click="fetchNotice" class="header-notice">
        <a-badge count="0">
          <div class="message">
            <img :src="require('@/assets/navbar/notice.png')" alt="消息" />
            <div v-if="noticeTotal > 0" class="redpot"></div>
          </div>
        </a-badge>
      </span>
    </a-popover>
    <!-- 消息详情页面 -->
    <DialogNotice ref="dialogNotice"></DialogNotice>
  </div>
</template>

<script>
import { getAction, putAction } from '@/api/manage'
import { formatTime } from '@/utils/index'
import store from '@/store/'
// 消息详情页面
import DialogNotice from '@/views/components/dialogNotice'
import Vue from 'vue'
import { USER_INFO, ACCOUNT_BOOK } from '@/store/mutation-types'

export default {
  name: 'SHeaderNotice',
  components: {
    DialogNotice,
  },
  props: {},
  data () {
    return {
      visible: false,
      loadding: false,
      url: {
        listCementByUser: '/sys/annountCement/getAccountBeyond',
        editCementSend: '/sys/sysAnnouncementSend/editByAnntIdAndUserId',
        queryById: '/sys/annountCement/queryById',
      },
      noticeTotal: 0, // 消息的总数
      noticeData: [], //消息的数据列表
      isLeader: 0,
    }
  },
  computed: {
    msgTotal () {
      return parseInt(this.msg1Count) + parseInt(this.msg2Count)
    },
  },
  mounted () {
    // console.log('HeaderNotice    initWebSocket')
    // 获取是否是leader
    this.getIsLeader()
    this.loadData()
    //this.timerFun();
    // console.log('HeaderNotice  mounted    initWebSocket')
    // this.initWebSocket()
    // this.heartCheckFun();
    // 监听接收消息
    const that = this
    this.$EventBus.$on('READNOTICE', function (res) {
      this.loadData()
    })
  },
  beforeDestroy () {
    this.$EventBus.$off('READNOTICE')
  },
  destroyed: function () {
    // 离开页面生命周期函数
    this.websocketOnclose()
  },
  methods: {
    fetchNotice () {
      if (this.loadding) {
        this.loadding = false
        return
      }
      this.loadding = true
      setTimeout(() => {
        this.loadding = false
      }, 2000)
    },
    // 更多消息
    moreNotice () {
      this.$router.push({ path: '/home/newsNotice' }).catch(err => { })
      this.visible = false
    },
    // 清空消息
    clearNotice () {
      getAction('/sys/annountCement/allToRead', {}).then((res) => {
        if (res.code === 200) {
          this.loadData()
        }
      })
    },
    // 跳转至详情
    toDetails (item) {
      this.toRead(item.id)
      this.$refs.dialogNotice.show(item)
    },
    // 消息已读
    toRead (id) {
      getAction('/sys/annountCement/toReadAccountBeyond', { id }).then((res) => {
        if (res.code === 200) {
          this.loadData()
        }
      })
    },
    timerFun () {
      this.stopTimer = false
      let myTimer = setInterval(() => {
        // 停止定时器
        if (this.stopTimer == true) {
          clearInterval(myTimer)
          return
        }
        this.loadData()
      }, 6000)
    },
    loadData () {
      try {
        // 获取系统消息
        getAction(this.url.listCementByUser, {
          pageSize: 2,
          pageNo: 1,
        })
          .then((res) => {
            if (res.success) {
              let data = res.result.records || []
              data.forEach((item) => {
                item.readMsg = item.readFlag === '1' ? '已读' : '未读'
              })
              this.noticeData = data
              this.noticeTotal = res.result.total
            }
          })
          .catch((error) => {
            // console.log('系统消息通知异常', error) //这行打印permissionName is undefined
            this.stopTimer = true
            // console.log('清理timer')
          })
      } catch (err) {
        this.stopTimer = true
        // console.log('通知异常', err)
      }
    },
    clickBuy () {
      // 暂未对接，页面跳转先注掉
      this.$elMessage.warning('该功能暂未开放！')
    },
    // 获取是否是leader
    getIsLeader () {
      let userInfo = Vue.ls.get(USER_INFO)
      getAction('/accountbookusing/xghAccountBookUserUsing/getUserIsLeader', {
        userId: userInfo.id,
      }).then(res => {
        this.isLeader = res.result
      })
    },
    showAnnouncement (record) {
      putAction(this.url.editCementSend, { anntId: record.id }).then((res) => {
        if (res.success) {
          this.loadData()
        }
      })
      this.hovered = false
      if (record.openType === 'component') {
        this.openPath = record.openPage
        this.formData = { id: record.busId }
        this.$refs.showDynamNotice.detail(record.openPage)
      } else {
        this.$refs.ShowAnnouncement.detail(record)
      }
    },
    toMyAnnouncement () {
      this.$router.push({
        path: '/isps/userAnnouncement',
      })
    },
    modalFormOk () { },
    handleHoverChange (visible) {
      this.hovered = visible
    },

    initWebSocket: function () {
      // console.log('initWebSocket')
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      var userId = store.getters.userInfo.id
      var url =
        window._CONFIG['domianURL'].replace('https://', 'wss://').replace('http://', 'ws://') + '/websocket/' + userId
      // console.log(url)
      this.websock = new WebSocket(url)
      this.websock.onopen = this.websocketOnopen
      this.websock.onerror = this.websocketOnerror
      this.websock.onmessage = this.websocketOnmessage
      this.websock.onclose = this.websocketOnclose
    },
    websocketOnopen: function () {
      // console.log('WebSocket连接成功')
      //心跳检测重置
      //this.heartCheck.reset().start();
    },
    websocketOnerror: function (e) {
      // console.log('WebSocket连接发生错误')
      this.reconnect()
    },
    websocketOnmessage: function (e) {
      // console.log('-----接收消息-------', e.data)
      var data = eval('(' + e.data + ')') //解析对象
      if (data.cmd == 'topic') {
        //系统通知
        let accountInfo = Vue.ls.get(ACCOUNT_BOOK) || {}
        if (data.msgTxt.indexOf(accountInfo.id) != -1) {
          this.loadData()
        }
      } else if (data.cmd == 'user') {
        //用户消息
        this.loadData()
      }
      //心跳检测重置
      //this.heartCheck.reset().start();
    },
    websocketOnclose: function (e) {
      // console.log('connection closed (' + e + ')')
      if (e) {
        // console.log('connection closed (' + e.code + ')')
      }
      this.reconnect()
    },
    websocketSend (text) {
      // 数据发送
      try {
        this.websock.send(text)
      } catch (err) {
        // console.log('send failed (' + err.code + ')')
      }
    },

    openNotification (data) {
      var text = data.msgTxt
      const key = `open${Date.now()}`
      this.$notification.open({
        message: '消息提醒',
        placement: 'bottomRight',
        description: text,
        key,
        btn: (h) => {
          return h(
            'a-button',
            {
              props: {
                type: 'primary',
                size: 'small',
              },
              on: {
                click: () => this.showDetail(key, data),
              },
            },
            '查看详情'
          )
        },
      })
    },

    reconnect () {
      var that = this
      if (that.lockReconnect) return
      that.lockReconnect = true
      //没连接上会一直重连，设置延迟避免请求过多
      setTimeout(function () {
        //console.info('尝试重连...')
        that.initWebSocket()
        that.lockReconnect = false
      }, 5000)
    },
    heartCheckFun () {
      var that = this
      //心跳检测,每20s心跳一次
      that.heartCheck = {
        timeout: 20000,
        timeoutObj: null,
        serverTimeoutObj: null,
        reset: function () {
          clearTimeout(this.timeoutObj)
          //clearTimeout(this.serverTimeoutObj);
          return this
        },
        start: function () {
          var self = this
          this.timeoutObj = setTimeout(function () {
            //这里发送一个心跳，后端收到后，返回一个心跳消息，
            //onmessage拿到返回的心跳就说明连接正常
            that.websocketSend('HeartBeat')
            // console.info('客户端发送心跳')
            //self.serverTimeoutObj = setTimeout(function(){//如果超过一定时间还没重置，说明后端主动断开了
            //  that.websock.close();//如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
            //}, self.timeout)
          }, this.timeout)
        },
      }
    },
    showDetail (key, data) {
      this.$notification.close(key)
      var id = data.msgId
      getAction(this.url.queryById, { id: id }).then((res) => {
        if (res.success) {
          var record = res.result
          this.showAnnouncement(record)
        }
      })
    },
    formatTime (val) {
      if (!val.sendTime) {
        return val.sendTime
      }
      return formatTime(Date.parse(val.sendTime))
    },
  },
}
</script>

<style lang="less" scoped>
.msg-title {
  margin-bottom: 13px;
  height: 20px;
  font-size: 14px;
  font-family: PingFangSC-Regular;
  line-height: 22px;
  color: #1993fb;
}

.title-line {
  margin: 0px -20px;
  width: 300px;
  height: 1px;
  background: rgba(232, 232, 232, 0.4);
}

.list {
  .item {
    .item-title {
      display: flex;
      justify-content: space-between;

      .title-left {
        margin-top: 17px;
        height: 20px;
        font-size: 14px;
        font-family: PingFangSC-Regular;
        line-height: 22px;
        color: rgba(0, 0, 0, 0.65);
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
      }

      .title-right {
        margin-top: 5px;
        width: 60px;
        height: 30px;
        background: rgba(253, 108, 33);
        border-radius: 5px;
        font-size: 14px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #ffffff;
        border-style: none;
      }
    }

    .item-content {
      margin-top: 3px;
      height: 17px;
      font-size: 12px;
      font-family: PingFangSC-Regular;
      line-height: 20px;
      color: rgba(0, 0, 0, 0.45);
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
    }

    .item-time {
      margin-top: 10px;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .time-left {
        height: 17px;
        font-size: 12px;
        font-family: PingFangSC-Regular;
        line-height: 20px;
        color: rgba(0, 0, 0, 0.45);
      }

      .time-right {
        height: 17px;
        font-size: 12px;
        font-family: HelveticaNeue;
        line-height: 20px;
        color: #1993fb;
      }
    }

    .item-line {
      margin-top: 7px;
      width: 100%;
      height: 1px;
      background: rgba(232, 232, 232, 0.4);
    }
  }
}

.bottom {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 53px;
  margin-bottom: -10px;

  .bottom-more {
    width: 50%;
    text-align: center;
    font-size: 14px;
    font-family: PingFangSC-Regular;
    height: 53px;
    color: #1993fb;
    border-style: none;
    background: rgba(0, 0, 0, 0);
  }

  .bottom-clear {
    width: 50%;
    text-align: center;
    font-size: 14px;
    font-family: PingFangSC-Regular;
    height: 53px;
    color: rgba(0, 0, 0, 0.65);
    border-style: none;
    background: rgba(0, 0, 0, 0);
  }
}

.header-notice {
  display: inline-block;
  transition: all 0.3s;
  display: flex;
  align-items: center;

  span {
    vertical-align: initial;
  }

  .message {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-left: 10px;
    position: relative;

    img {
      width: 21px;
      height: 20px;
    }

    .redpot {
      position: absolute;
      top: 3px;
      left: 12px;
      width: 5px;
      height: 5px;
      background: #ff0000;
      border-radius: 50%;
      opacity: 1;
    }
  }
}
</style>
